<template>
	<view class="app">
		<image class="bgImg" src="../../static/bg.png"></image>
		<view class="searchView" v-if="showCtrlView==false">
			<image class="top_window" src="../../static/hw_logo_top.png" mode="widthFix"></image>
			<label class="des">
				<text>{{$t('index.hw.hinsOne')}}
					{{$t('index.hw.hinsTwo')}}</text>
			</label>
			<view class="searchBtn" @click="searchAction()">
				<image class="searchBg" src="../../static/button_bg.png" mode="widthFix"></image>
				<label class="searchText">
					<text>{{$t('index.hw.search')}}</text>
				</label>
			</view>
		</view>
		<view class="content" v-if="showCtrlView">
			<image v-if="!isMP()" class="ctrl_top_window" src="../../static/hw_logo_top.png" mode="aspectFit"></image>
			<image v-if="isMP()" class="ctrl_top_window" src="../../static/hw_logo_top.png" mode="widthFix"></image>
			<view class="stateView">
				<image class="better" v-show="better>80" src="../../static/better_0.png"></image>
				<image class="better" v-show="better>60&&better<=80" src="../../static/better_1.png"></image>
				<image class="better" v-show="better>40&&better<=60" src="../../static/better_2.png"></image>
				<image class="better" v-show="better>20&&better<=40" src="../../static/better_3.png"></image>
				<image class="better" v-show="better<=20" src="../../static/better_4.png"></image>
				<text class="betterDes">{{''+better+'%'+''}}</text>
				<!-- <image class="water" v-show="water<20" src="../../static/water_low.png"></image>
				<text class="betterDes" v-show="water<20">缺液</text> -->
			</view>
			<view>
				<view class="section">
					<text class="sectionTitle">{{$t('index.water')}}</text>
					<view class="sliderView">
						<view class="dangDiv">
							<view class="dang" @click="setDang(1)">1</view>
							<view class="dang" @click="setDang(2)">2</view>
							<view class="dang" @click="setDang(3)">3</view>
							<view class="dang" @click="setDang(4)">4</view>
							<view class="dang" @click="setDang(5)">5</view>
						</view>
						<slider activeColor="#BE9F88" backgroundColor="#FAF7FF" blockColor="#E9D8CD" blockSize="28"
							@change="sliderChange" max="5" min="1" step="1" style="margin:15px 10% auto 10%;"
							:value="level"></slider>
					</view>
				</view>
				<view class="section" v-show="deviceType=='H5'">
					<text class="sectionTitle">{{$t('index.model')}}</text>
					<view class="modalView">
						<uni-section :title="emojy" titleFontSize="16px" v-slot:right >
							<switch :checked="showExpression" color="#BE9F88" @change="showExpressionChange"
								slot="right"></switch>
						</uni-section>
						<view class="line"></view>
<!-- 						<uni-section title="震动感应" titleFontSize="16px" v-slot:right>
							<switch :checked="shake" color="#BE9F88" @change="shakeChange" slot="right">
							</switch>
						</uni-section>
						<view class="line"></view> -->
						<uni-section :title="cleanName" titleFontSize="16px" v-slot:right>
							<switch :checked="clean" color="#BE9F88" @change="cleanChange" slot="right">
							</switch>
						</uni-section>
					</view>
					<view style="height:40px;"></view>
				</view>
				<view class="section" v-show="deviceType=='H3'">
					<text class="sectionTitle">{{$t('index.model')}}</text>
					<view class="modalView">
						<!-- <uni-section title="表情" titleFontSize="16px" v-slot:right >
							<switch :checked="showExpression" color="#BE9F88" @change="showExpressionChange"
								slot="right"></switch>
						</uni-section>
						<view class="line"></view> -->
<!-- 						<uni-section title="震动感应" titleFontSize="16px" v-slot:right>
							<switch :checked="shake" color="#BE9F88" @change="shakeChange" slot="right">
							</switch>
						</uni-section>
						<view class="line"></view> -->
						<uni-section :title="cleanName" titleFontSize="16px" v-slot:right>
							<switch :checked="clean" color="#BE9F88" @change="cleanChange" slot="right">
							</switch>
						</uni-section>
					</view>
					<view style="height:40px;"></view>
				</view>
			</view>
		</view>
		
		
		<view>
			<!--l蓝牙列表弹窗-->
			<uni-popup ref="popup">
				<uni-card is-shadow="true" padding="0" spacing="0">
					<view class="dialogTitle">{{$t('index.deviceList')}}</view>
					<scroll-view scroll-y="true">
						<view class="popup-content" style="color: black;width: 70vw;">
							<uni-list>
								<view v-for="(device,index) in bluetoothList" :key="index">
									<uni-list-item :title=" deviceName +  device.name" :note="'id：' + device.deviceId" link
										@click="clickListItem(index)">
											<template v-slot:footer >
												<view v-show="device.isChoose == true" style="margin-top: 22px;">
													<uni-icons type="checkmarkempty" size="30" ></uni-icons>
												</view>
											</template>
									</uni-list-item>
								</view>
							</uni-list>
						</view>
					</scroll-view>
				</uni-card>
			</uni-popup>
		</view>

	</view>
</template>

<script>
	function ab2hex(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	}
	export default {
		data() {
			return {
				loading: false,
				emojy: "表情",
				cleanName: "清洁模式",
				deviceName: '设备蓝牙名称：',
				loadingText: "搜索",
				//蓝牙列表
				bluetoothList: [],
				//蓝牙三件套
				deviceId: "",
				uuid: "",
				characteristics: "",
				showCtrlView: false,
				level: 1,
				showExpression: false,
				clean: false,
				shake: false,
				better: 100,
				// 电量
				water: 100,
				
				deviceType: 'H5'
			}
		},
		onLoad() {
			var that = this;
			this.emojy = this.$t('index.emojy')
			this.cleanName = this.$t('index.clean')
			this.deviceName = this.$t('index.deviceName')
			
			const disconnect = this.$t('index.disconnect')
			uni.onBLEConnectionStateChange(function(res) {
				if (res.connected == false) {
					uni.showToast({
						title: disconnect,
						icon: "none",
						duration: 2e3
					});
					that.deviceId = "";
					that.uuid = "";
					that.characteristics = "";
					that.showCtrlView = false;
				}
			});
		},
		onShow: function() {
			const mess = this.$t('index.hins')  
			const ok = this.$t('index.ok')
			
			uni.openBluetoothAdapter({
				success: function(res) { // 开启蓝牙成功
					console.log('已经开启蓝牙权限')
				},
				fail: function(msg) {
					console.log(msg.errMsg)
					uni.showModal({
						content: mess, 
						showCancel: false,
						confirmText: ok,
						confirmColor: '#3e90fa',
						success: res => {
							if (res.confirm) {
							
							}
						}
					})
				}
			})
		},
		beforeDestroy() {
			uni.closeBluetoothAdapter({
				success(res) {
					console.log(res)
				}
			})
		},
		methods: {
			clickListItem(index) {
				let item = this.bluetoothList[index]
				item.isChoose = true;
				let that = this;
				const connecting = this.$t('index.connecting')
				setTimeout(function() {
					that.deviceId = item.deviceId;
					that.connetBleBluetooth();
					that.$refs.popup.close();
					uni.showLoading({
						title: connecting
					});
				}, 500);
			},
			showBLEListDialog() {
				this.$refs.popup.open('center')
			},
			shakeChange(e) {
				this.shake = e.detail.value;
				this.writeInfoToBluetooth("04", e.detail.value == true ? "01" : "00");
			},
			showExpressionChange(e) {
				this.showExpression = e.detail.value;
				this.writeInfoToBluetooth("02", e.detail.value == true ? "01" : "00");
			},
			cleanChange(e) {
				var that = this;
				const content = this.$t('index.cleanHins')
				const cancel = this.$t('cancel')
				const sure = this.$t('sure')
				if (e.detail.value) {
					uni.showModal({
						content: content,
						cancelText: cancel,
						confirmText: sure,
						confirmColor: "#3e90fa",
						success: function success(res) {
							if (res.confirm) {
								that.clean = e.detail.value;
								that.writeInfoToBluetooth("03", e.detail.value == true ? "01" : "00");
							}
							if (res.cancel) {
								that.clean = false;
							}
						}
					});
				} else {
					this.clean = e.detail.value;
					this.writeInfoToBluetooth("03", e.detail.value == true ? "01" : "00");
				}
			},
			sliderChange(e) {
				console.log("value 发生变化：" + e.detail.value);
				this.level = e.detail.value;
				this.writeInfoToBluetooth("01", "0" + e.detail.value);
			},
			setDang(dang) {
				this.level = dang;
				this.writeInfoToBluetooth("01", "0" + dang);
			},
			searchAction() {
				if (this.loading) {
					this.stopSearchAction();
				} else {
					this.seachAction();
				}
			},
			// 开始搜索
			seachAction() {
				const searching = this.$t('index.searching')
				this.loading = true;
				this.loadingText = searching;
				uni.showLoading({
					title: this.loadingText
				});
				this.bluetoothList = [];
				var that = this;
				uni.startBluetoothDevicesDiscovery({
					success: function success(res) {
						//services: ['0000FFF0', '0000ffe0'],
						uni.onBluetoothDeviceFound(function(el) {
							console.log("搜索到设备---", el.devices);
							el.devices.forEach(function(item, index) {
								if (item.name.includes("fungeneH") && item.name.length == 10 ) {
									that.$set(item, "isChoose", false);
									console.log("搜索到设备---", item);
									uni.hideLoading();
									that.bluetoothList.push(item);
									that.showBLEListDialog();
								}
							});
						});
					}
				});
			},
			// 关闭搜索
			stopSearchAction() {
				this.loading = false;
				this.loadingText = "搜索";
				uni.stopBluetoothDevicesDiscovery({
					success: function success(res) {
						console.log("停止搜索---", res);
					},
					fail: function fail(res) {
						console.log("停止搜索失败---", res);
					}
				});
			},
			// 连接Ble蓝牙 
			connetBleBluetooth() {
				var that = this;
				var devId = this.deviceId;
				uni.createBLEConnection({
					deviceId: devId,
					success: function success(res) {
						//需延时连接，不然会报错
						setTimeout(function() {
							uni.getBLEDeviceServices({
								deviceId: that.deviceId,
								success: function success(res) {
									that.uuid = res.services[0].uuid;
									that.getBluetoothInfo();
								}
							});
						}, 1000);
					},
					fail: function fail(res) {
						uni.hideLoading();
					}
				});
			},
			// 获取蓝牙信息
			getBluetoothInfo() {
				var that = this;
				uni.getBLEDeviceCharacteristics({
					deviceId: this.deviceId,
					serviceId: this.uuid,
					success: function success(res) {
						console.log("特征值characteristics1=" + res.characteristics[0].uuid);
						console.log("特征值characteristics2=" + res.characteristics[1].uuid);
						that.characteristics = res.characteristics[1].uuid;
						that.notifcation();
						that.stopSearchAction();
						//关闭搜索
						setTimeout(function() {
							that.writeInfoToBluetooth("77", "cc");
						}, 200);
						that.showCtrlView = true;
						uni.hideLoading();
					},
					fail: function fail(res) {
						uni.hideLoading();
					}
				});
			},
			//订阅  监听
			notifcation() {
				var that = this;
				var deviceId = this.deviceId;
				var serviceId = this.uuid;
				var characteristicId = this.characteristics;
				console.log("deviceId=" + deviceId);
				console.log("serviceId=" + serviceId);
				console.log("characteristicId=" + characteristicId);
				uni.notifyBLECharacteristicValueChange({
					state: true,
					// 启用 notify 功能
					// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
					deviceId: deviceId,
					// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
					serviceId: serviceId,
					// 这里的 characteristicId 需要在 getBLEDeviceCharacteristics 接口中获取
					characteristicId: characteristicId,
					success: function success(res) {
						console.log("订阅监听成功", res.errMsg);
						that.onValueChange();
					},
					fail: function fail(res) {
						console.log("订阅监听失败", res.errMsg);
					}
				});
			},
			// 监听数值变化
			onValueChange() {
				//            档位    表情  自清洁   震动   电量    
				//格式  66bb    01    00    01      02     088
				var that = this;
				uni.onBLECharacteristicValueChange(function(res) {
					var result = ab2hex(res.value);
					console.log(result);
					if (result.includes("66bb")) {
						result = result.replace("66bb", "");
						that.deviceType = 'H5';
						//型号
						that.level = parseInt(result.substr(0, 2));
						//档位
						that.showExpression = parseInt(result.substr(2, 2));
						// 表情 
						that.clean = parseInt(result.substr(4, 2));
						//自清洁
						that.shake = parseInt(result.substr(6, 2));
						//震动
						that.better = parseInt(result.substr(8, 4));
						//电量
						that.water = parseInt(result.substr(12, 2));
						//液量
						// uni.showToast({
						// 	title: '收到蓝牙讯号' + result,
						// 	icon: 'none',
						// 	duration: 2000
						// })
					}else if(result.includes('44bb')){
						result = result.replace("44bb", "");
						that.deviceType = 'H3';
						//型号
						that.level = parseInt(result.substr(0, 2));
						//档位
						that.clean = parseInt(result.substr(4, 2));
						//自清洁
						that.better = parseInt(result.substr(8, 4));
						//电量
					}
					
				});
			},
			// 写数据
			// type  1是档位控制   2 是表情开关   3是自清洁
			writeInfoToBluetooth(type, value) {
				const btHins = this.$t('btHins')
				if (this.deviceId == "") {
					uni.showToast({
						title: btHins,
						icon: "none",
						duration: 2e3
					});
					return;
				}
				var hex = "66 bb" + type + value;
				//要发送的信息
				var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function(h) {
					return parseInt(h, 16);
				}));
				console.log(typedArray);
				var buffer1 = typedArray.buffer;
				var devId = this.deviceId;
				var uuid = this.uuid;
				var chartId = this.characteristics;
				uni.writeBLECharacteristicValue({
					deviceId: devId,
					serviceId: uuid,
					characteristicId: chartId,
					value: buffer1,
					writeType: "writeNoResponse",
					success: function success(res) {
						console.log("蓝牙写入成功", res.errMsg);
					},
					fail: function fail(res) {
						console.log("写入失败--------", res);
					}
				});
			},
			isMP() {
				// #ifdef  APP-PLUS
					return false
				// #endif
				return true;
			},
			onShareAppMessage() {},
			onShareTimeline() {}
		}
	}
</script>

<style lang="scss">
	.app {
		width: 100%
	}

	.content {
		display: flex;
		flex-direction: column
	}

	.logo {
		height: 200rem;
		margin-top: 200rem;
		width: 200rem
	}

	.serach {
		text-align: center
	}

	.serach {
		margin-top: 50px;
		width: 380px
	}

	.water {
		height: 21px;
		margin-left: 10px;
		margin-top: 3px;
		width: 16px
	}

	.sliderView {
		height: 100px
	}

	.sliderView {
		background-color: hsla(0, 0%, 100%, .5);
		border-radius: 10px;
		margin: 5px 15px auto
	}

	.modalView {
		height: auto;
		padding-bottom: 4px;
		margin: 0 12px;
		background-color: rgba(255, 255, 255, 0.5);
		border-radius: 10px;
		margin: 5px 15px auto
	}

	.dangDiv {
		display: flex;
		flex-direction: row
	}

	.dang {
		background-color: hsla(0, 0%, 100%, .5);
		color: #70523c;
		font-size: 28px;
		height: auto;
		margin-top: 5px;
		opacity: .2;
		text-align: center;
		width: 20%
	}

	.rowBtn {
		width: 77%
	}

	.line {
		background-color: #b19581;
		height: .8px;
		margin-top: 5px;
		margin-left: 10px;
		margin-right: 10px;
		border-radius: 0.4px;
	}

	.stateView {
		display: flex;
		flex-direction: row;
		height: 25px;
		margin-left: 67%;
		margin-top: 65%;
		position: absolute;
		width: 120px
	}

	.sectionTitle {
		color: #92735c;
		font-size: 12px;
		margin-left: 15px
	}

	.better {
		height: 24px;
		width: 11px
	}

	.betterDes {
		font-size: 12px;
		margin-left: 7px;
		margin-top: 9px
	}

	.section {
		margin-bottom: 15px;
		margin-top: 15px
	}

	.ctrl_top_window {
		margin: 30px 30% auto;
		max-width: 40%;
		padding-top: 5px
	}

	.searchView {
		align-items: center;
		display: flex;
		flex-direction: column;
		justify-content: center
	}

	.bgImg {
		height: 100%;
		left: 0;
		position: fixed;
		top: 0;
		width: 100%;
		z-index: -1
	}

	.top_window {
		margin: 30px 15% auto;
		max-width: 70%
	}

	.des {
		font-size: 14px;
		margin-top: 15px;
		text-align: center
	}

	.searchBtn {
		align-items: center;
		border-radius: 24px;
		justify-content: center;
		margin-bottom: 50px;
		margin-top: 55px;
	}

	.searchBg {
		display: flex;
		height: 48px;
		width: 188px
	}

	.searchText {
		position: absolute;
		height: 48px;
		width: 188px;
		text-align: center;
		margin-top: -40px;
	}

	.popup-content {
		height: 248px;
	}
	.dialogTitle {
		font-size: 16px;
		text-align: center;
		height: 35px;
		padding-top: 10px;
	}
</style>
